package com.xqboss.apps.controller.consumer;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.consumer.*;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.consumer.ConsumerFriendDto;
import com.xqboss.apps.dto.consumer.ConsumerFriendsApplyDto;
import com.xqboss.apps.dto.marketing.AppGetAirdropListDto;
import com.xqboss.apps.dto.system.SysAnnouncementMsgDto;
import com.xqboss.apps.enums.consumer.ConsumerApplyStatusEnum;
import com.xqboss.apps.service.consumer.*;
import com.xqboss.apps.service.marketing.AirdropRecordService;
import com.xqboss.apps.service.sys.SysAnnouncementMsgService;
import com.xqboss.apps.service.sys.SysHistoryActivityService;
import com.xqboss.apps.vo.consumer.ConsumerContactsVo;
import com.xqboss.apps.vo.consumer.ConsumerFriendsApplyVo;
import com.xqboss.apps.vo.consumer.ConsumerFriendsVo;
import com.xqboss.apps.vo.marketing.AppAirdropRecordVo;
import com.xqboss.apps.vo.sys.SysAnnouncementMsgVo;
import com.xqboss.apps.vo.sys.SysHistoryActivityVo;
import com.xqboss.common.annotation.RepeatSubmit;
import com.xqboss.common.core.controller.BaseController;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.page.PageDomain;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.utils.sql.SqlUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 好友Controller
 *
 * @author xqboss
 * @date 2023-08-08
 */
@Api(tags = {"好友管理"})
@RestController
@RequestMapping("/apps/consumer/friend")
public class ConsumerFriendsController extends BaseController {

    @Autowired
    private ConsumerFriendsService consumerFriendsService;
    @Autowired
    private ConsumerFriendsApplyService consumerFriendsApplyService;
    @Autowired
    private ConsumerContactsService consumerContactsService;
    @Autowired
    private ConsumerTeamApplyService consumerTeamApplyService;
    @Autowired
    private ConsumerTeamService consumerTeamService;
    @Autowired
    private ConsumerInteractMsgService consumerInteractMsgService;
    @Autowired
    private SysAnnouncementMsgService sysAnnouncementMsgService;
    @Autowired
    private SysHistoryActivityService sysHistoryActivityService;
    @Autowired
    private AirdropRecordService airdropRecordService;
    @Autowired
    private RedisCache redisCache;


    @ApiOperation("队伍-邀请好友列表")
    @PostMapping("/list")
    public R<List<ConsumerFriendsVo>> list(@RequestBody ConsumerFriendDto dto) {
        if (ObjUtil.isNull(dto.getTeamId())) {
            return R.fail("队伍不能为空");
        }
        dto.setUserId(getUserId());
        dto.startPageAndOrder();
        List<ConsumerFriendsVo> vos = consumerFriendsService.friendsList(dto);
        return R.ok(vos);
    }

    @ApiOperation("添加好友-搜索")
    @GetMapping("/add-search/{keyword}")
    public R<ConsumerFriendsVo> addSearch(@PathVariable("keyword")
                       @ApiParam(value = "搜索关键字", required = true)
                       @NotBlank(message = "请输入关键字")
                       String keyword) {
        Long userId = getUserId();
        return consumerFriendsService.addSearch(keyword, userId);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("添加好友")
    @GetMapping("/add/{receiveUserId}")
    public R add(@PathVariable("receiveUserId")
                       @ApiParam(value = "被添加用户id", required = true)
                       @NotBlank(message = "请输入添加用户id")
                       Long receiveUserId) {
        Long userId = getUserId();
        return consumerFriendsApplyService.add(userId, receiveUserId);
    }

    @ApiOperation("我的好友列表")
    @PostMapping("/list-me")
    public R<List<ConsumerFriendsVo>> listMe(@RequestBody ConsumerFriendDto dto) {
        dto.setUserId(getUserId());
        dto.startPage();
        List<ConsumerFriendsVo> vos = consumerFriendsService.friendsListMe(dto);
        return R.ok(vos);
    }

    @ApiOperation("我的通讯录列表")
    @PostMapping("/contacts-list")
    public R<List<ConsumerContactsVo>> contactsList(PageDto dto) {
        dto.startPage();
        List<ConsumerContactsVo> vos = consumerContactsService.contactsList(getUserId());
        return R.ok(vos);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("编辑好友")
    @PutMapping("/edit")
    public R edit(@RequestBody ConsumerFriendDto dto) {
//        dto.setUserId(getUserId());
        ConsumerFriends friends = new ConsumerFriends();
        friends.setId(dto.getId());
        friends.setReamrks(dto.getReamrks());
        consumerFriendsService.updateById(friends);
        return R.ok();
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("删除好友")
    @DeleteMapping("/delete")
    public R delete(@RequestBody ConsumerFriendDto dto) {
        dto.setUserId(getUserId());
        ConsumerFriends result = consumerFriendsService.getById(dto.getId());
        if (ObjUtil.isNull(result)) {
            return R.fail("资源不存在");
        }
        consumerFriendsService.removeById(dto.getId());

        LambdaQueryWrapper<ConsumerFriends> wq = new LambdaQueryWrapper<>();
        wq.eq(ConsumerFriends::getUserId, result.getFriendUserId());
        wq.eq(ConsumerFriends::getFriendUserId, dto.getUserId());
        consumerFriendsService.remove(wq);
        return R.ok();
    }

    @ApiOperation("好友申请列表")
    @PostMapping("/apply-list")
    public R<List<ConsumerFriendsApplyVo>> applyList(@RequestBody ConsumerFriendsApplyDto dto) {
        dto.startPageAndOrder();
        List<ConsumerFriendsApplyVo> vos = consumerFriendsApplyService.friendsApplyList(dto);
        return R.ok(vos);
    }

    @RepeatSubmit(interval = 1000, justUrl = true)
    @ApiOperation("编辑好友申请列表")
    @PutMapping("/edit-apply-list")
    public R editApplyList(@RequestBody ConsumerFriendsApplyDto dto) {
        dto.setInitUserId(getUserId());
        return consumerFriendsApplyService.edit(dto);
    }

    @ApiOperation("新朋友/队伍申请数量")
    @GetMapping("/new-team-count")
    public R newTeamCount() {
        Long userId = getUserId();
        //好友申请
        LambdaQueryWrapper<ConsumerFriendsApply> wq = new LambdaQueryWrapper<>();
        wq.eq(ConsumerFriendsApply::getReceiveUserId, userId);
        wq.eq(ConsumerFriendsApply::getStatus, ConsumerApplyStatusEnum.PENDING.getValue());
        long newFriendCount = consumerFriendsApplyService.count(wq);

        //队伍申请
        LambdaQueryWrapper<ConsumerTeamApply> wr = new LambdaQueryWrapper<>();
        wr.eq(ConsumerTeamApply::getHandlerUserId, userId);
        wr.eq(ConsumerTeamApply::getStatus, ConsumerApplyStatusEnum.PENDING.getValue());
        long teamCount = consumerTeamApplyService.count(wr);

        //我的好友人数
        LambdaQueryWrapper<ConsumerFriends> friendWq = new LambdaQueryWrapper<>();
        friendWq.eq(ConsumerFriends::getUserId, userId);
        long friendNum = consumerFriendsService.count(friendWq);

        //我的队伍信息
        LambdaQueryWrapper<ConsumerTeam> wra = new LambdaQueryWrapper<>();
        wra.eq(ConsumerTeam::getCreateUserId, userId);
        ConsumerTeam team = consumerTeamService.getOne(wra);

        //互动消息
        LambdaQueryWrapper<ConsumerInteractMsg> interactWq = new LambdaQueryWrapper<>();
        interactWq.eq(ConsumerInteractMsg::getUserId, userId);
        interactWq.eq(ConsumerInteractMsg::getStatus, 0);
        long interactCount = consumerInteractMsgService.count(interactWq);

        //公告消息
        SysAnnouncementMsgDto dto = new SysAnnouncementMsgDto();
        dto.setUserId(userId);
        List<SysAnnouncementMsgVo> announcementMsg = sysAnnouncementMsgService.findByList(dto);
        long announcementCount = announcementMsg.stream().filter(item -> item.getIsRead() == 0).count();

        //历史活动消息
        List<SysHistoryActivityVo> historyList = sysHistoryActivityService.historyList(userId);
        long historyCount = historyList.stream().filter(item -> item.getIsRead() == 0).count();

        // 礼物未读数量
        Integer unreadGiftCount = redisCache.getCacheObject(RedisKey.KEY_USER_UNREAD_GIFT + userId);

        Map<String, Object> map = new HashMap<>();
        map.put("newFriendCount", newFriendCount); //好友申请
        map.put("announcementCount", announcementCount); //公告消息
        map.put("historyCount", historyCount); //历史活动消息数量
        map.put("airdropCount", unreadGiftCount == null ? 0 : unreadGiftCount); // 礼物记录消息数量
        map.put("interactCount", interactCount); //互动消息数量
        map.put("friendNum", friendNum); //我的好友人数
        map.put("teamCount", teamCount); //队伍申请
        map.put("teamId", team);//我的队伍信息

        return R.ok(map);
    }
}

